﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Sonic.Framework.Site
{
    public class Concatenation
    {
        public bool DeleteSourceFiles
        {
            get;
            set;
        }

        public List<SitePath> Paths
        {
            get;
            set;
        }

        public FileInfo OutputFilePath
        {
            get;
            set;
        }

        public Concatenation()
        {
            Paths = new List<SitePath>();
        }

        /// <summary>
        /// Concatenate all the file specified in the Paths list.
        /// </summary>
        /// <returns>FileInfo of the output concatenated file</returns>
        public FileInfo Concatenate()
        {
            StreamWriter sw = null;

            try
            {
                sw = new StreamWriter(OutputFilePath.FullName, false, UTF8Encoding.UTF8);

                foreach (Site.SitePath path in Paths)
                {
                    StreamReader sr = null;
                    try
                    {
                        sr = new StreamReader(path.FileInfo.FullName);
                        sw.Write(sr.ReadToEnd());
                        //sw.WriteLine();
                    }
                    catch (FileNotFoundException)
                    {
                        // File not found
                    }
                    catch (Exception ex)
                    {
                        // General exception
                    }
                    finally
                    {
                        if (sr != null)
                        {
                            sr.Close();
                        }
                    }

                    if (DeleteSourceFiles)
                    {
                        path.FileInfo.Delete();
                    }
                }
            }
            catch (DirectoryNotFoundException dirNotFoundEx)
            {
                // Directory not found
                NLog.LogManager.GetCurrentClassLogger().Error("Directory not found " + OutputFilePath.DirectoryName + "\n" + dirNotFoundEx.Message);
            }
            catch (Exception ex)
            {
                // Log exception
                NLog.LogManager.GetCurrentClassLogger().Error(ex.Message);
            }
            finally
            {
                if (sw != null)
                {
                    sw.Close();
                }
            }

            return OutputFilePath;
        }
    }
}
